# Path configurations
CUDA_INSTALL_PATH ?= /usr
CUDA_INCLUDE_PATH ?= $(CUDA_INSTALL_PATH)/include
CUDA_LIBRARY_PATH ?= $(CUDA_INSTALL_PATH)/lib64
CUDA_SDK_PATH     ?= $(HOME)/NVIDIA_GPU_Computing_SDK

I3D_INCLUDE_PATH  := /usr/local/include/i3d
LIB_ARCH          := $(shell uname -m)

ifdef cuda-install
	CUDA_INSTALL_PATH := $(cuda-install)
endif

# CUDA architecture configuration (at least 11 required)
CUDA_ARCH         := 20

# Compilers
CXX := g++ -fPIC
CC := gcc -fPIC
LINK := g++ -fPIC
NVCC := $(CUDA_INSTALL_PATH)/bin/nvcc -Xptxas -v -m64 -DUNIX -gencode=arch=compute_$(CUDA_ARCH),code=\"sm_$(CUDA_ARCH),compute_$(CUDA_ARCH)\"

# Includes
INCLUDES = -I. -I$(CUDA_INCLUDE_PATH) -I$(CUDA_SDK_PATH)/C/common/inc -I$(I3D_INCLUDE_PATH) -I$(CUDA_SDK_PATH)/shared/inc

# Linked libraries
LIB_CUDA := -L/usr/lib -L/usr/local/lib/ -L$(CUDA_SDK_PATH)/C/lib -L$(CUDA_SDK_PATH)/C/common/lib/linux -L$(CUDA_SDK_PATH)/shared/lib -lcudart -li3dcore -li3dalgo
#-lcutil_$(LIB_ARCH)$(LIBSUFFIX) -lshrutil_$(LIB_ARCH)$(LIBSUFFIX)

# Common flags
COMMONFLAGS += $(INCLUDES)
NVCCFLAGS += $(COMMONFLAGS)
CXXFLAGS += $(COMMONFLAGS)
CFLAGS += $(COMMONFLAGS)

# Debug modifiers
ifeq ($(dbg),1)
	COMMONFLAGS += -g
	NVCCFLAGS   += -D_DEBUG
	CXXFLAGS    += -D_DEBUG
	CFLAGS      += -D_DEBUG
	BINSUBDIR   := debug
	LIBSUFFIX   := D
else
	COMMONFLAGS += -O2
	BINSUBDIR   := release
	LIBSUFFIX   :=
	NVCCFLAGS   += --compiler-options -fno-strict-aliasing
	CXXFLAGS    += -fno-strict-aliasing
	CFLAGS      += -fno-strict-aliasing
endif

# Object files
OBJ_DIR = obj
OBJS = $(OBJ_DIR)/main.cpp.o $(OBJ_DIR)/gcuda.cu.o
TARGET = cuda-granulo
LINKLINE = $(LINK) -o $(TARGET) $(OBJS) $(LIB_CUDA) -u MAIN__
VPATH = src

# Compilation rules
.SUFFIXES: .c .cpp .cu .o

%/.sentinel:
	$(foreach d,$(subst /, ,$*),mkdir -p $d && cd $d && ):
	touch $@

$(OBJ_DIR)/%.c.o: %.c $(OBJ_DIR)/.sentinel
	$(CC) $(CFLAGS) -c $< -o $@

$(OBJ_DIR)/%.cu.o: %.cu $(OBJ_DIR)/.sentinel
	$(NVCC) $(NVCCFLAGS) -o $@ -c $<

$(OBJ_DIR)/%.cpp.o: %.cpp $(OBJ_DIR)/.sentinel
	$(CXX) $(CXXFLAGS) -c $< -o $@

$(TARGET): $(OBJS) Makefile
	$(LINKLINE)

clean :
	rm -f $(OBJS)
